package life.mahu.community.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import life.mahu.community.mapper.AdminMapper;
import life.mahu.community.model.Admin;
import life.mahu.community.model.AdminExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 小贱
 * @create 2019-12-30 20:20
 */
@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    public List<Admin> searchAdminUser(String userName) {

        AdminExample example = new AdminExample();
        AdminExample.Criteria criteria = example.createCriteria();
        criteria.andUserNameEqualTo(userName);
        return adminMapper.selectByExample(example);

    }

    public Admin searchUserById(Integer id) {

        return adminMapper.selectByPrimaryKey(id);
    }

    public Boolean delAdminUserById(Integer id) {
        int delUser = adminMapper.deleteByPrimaryKey(id);
        return delUser>0?true:false;
    }

    public PageInfo getAdminUserListPage(Admin user, Integer page, Integer limit) {
        AdminExample userExample = new AdminExample();
        AdminExample.Criteria criteria = userExample.createCriteria();
        if (user.getId() != null && user.getId() != 0) {
            criteria.andIdEqualTo(user.getId());
        }
        if (!(user.getUserName() == null || "".equals(user.getUserName()))) {
            criteria.andUserNameLike("%" + user.getUserName() + "%");
        }
        PageHelper.startPage(page, limit);
        List<Admin> userList = adminMapper.selectByExample(userExample);
        return new PageInfo<Admin>(userList);
    }

    public Admin getAdminUserById(Integer id) {
        return adminMapper.selectByPrimaryKey(id);
    }

    public Boolean insertUser(Admin user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        int insert = adminMapper.insert(user);
        return insert>0?true:false;
    }

    public Boolean updateUserByUserId(Admin user) {
        Admin loseUser = adminMapper.selectByPrimaryKey(user.getId());
        user.setPassword(loseUser.getPassword());
        int update = adminMapper.updateByPrimaryKey(user);
        return update>0?true:false;
    }

    public boolean isExit(String userName) {
        AdminExample userExample = new AdminExample();
        AdminExample.Criteria criteria = userExample.createCriteria();
        criteria.andUserNameEqualTo(userName);
        return adminMapper.selectByExample(userExample).size() != 0;
    }
}
